<?php

namespace App\Api\Dao;

use App\Exceptions\DaoException;
use App\Helpers\ResponseEnum;
use App\Models\TongDistrict;
use App\Models\TongUserAddress;

class UserAddressDao extends BaseDao
{

    /**
     * 查询构造器
     * @param $data
     * @return \Illuminate\Database\Eloquent\Builder
     */
    function getBuildQuery($data)
    {
        // TODO: Implement getBuildQuery() method.
        $query= TongUserAddress::query();

        if(checkIsHasField($data,'id')){
            $query->where('id',$data['id']);
        }
        if(checkIsHasField($data,'u_id')){
            $query->where('u_id',$data['u_id']);
        }
        return $query;
    }

    /**
     * 添加搜获地址
     * @param $data
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|true
     */
    public function addAddress($data){
        if(checkIsHasField($data,'id')){
            $id = $data['id'];
            unset($data['id']);
            $result = TongUserAddress::query()->where('id',$id)->update($data);
            if($result){
                TongUserAddress::query()->where('u_id',$data['u_id'])->where('id','!=',$id)->update([
                    'is_default'=>0
                ]);
            }
        }else{
            $result = TongUserAddress::query()->create($data);
        }

        if(!$result){
            throw new DaoException(ResponseEnum::HTTP_ERROR);
        }
        return $result;
    }

    /**
     * 获取收获地址
     * @param array $array
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection|void
     */
    public function getAddress(array $array)
    {
        return $this->getBuildQuery($array)->get();
    }

    /**
     * @param array $params
     * @return mixed
     * @throws DaoException
     */
    public function delAddress(array $params)
    {
        $result = $this->getBuildQuery($params)->delete();
        if(!$result){
            throw new DaoException(ResponseEnum::HTTP_ERROR);
        }
        return $result;
    }

    /**
     * @param array $params
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|void
     */
    public function getAddressInfo(array $params)
    {
        return $this->getBuildQuery($params)->first();
    }

}
